package com.study;

import org.junit.Test;

import java.io.*;

/**
 * @author:李雄
 * @ClassName:TestObjectOutputStream
 * @Description:
 * @createTime:2022-08-20 21:09
 */
public class TestObjectOutputStream {


    //将内存中的java对象保存到磁盘或通过网络传输出去
    // ObjectOutputStream实现
    @Test
    public void testObjectOutputStream() {

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            oos.writeObject(new String("我爱我的皮皮"));

            oos.flush();//刷新操作
            oos.writeObject(new Person("皮皮",23));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //反序列化，将磁盘文件中的对象还原为内存中的一个Java对象
    @Test
    public void testTestObjectInputStream() {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));
            Object obj = ois.readObject();
            String str = (String) obj;
            Person person = (Person) ois.readObject();
            System.out.println(str);
            System.out.println(person);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
